<template>
  <view class="my-settle-container">
    <!-- 全选 -->
    <label class="radio" @click="changeAllState">
      <radio color="#c00000" :checked="allChecked" /><text>全选</text>
    </label>
    <!-- 合计 -->
    <view class="amount-box">
      合计:<text class="amount">￥{{checkedAllPrice | toFixed}}</text>
    </view>
    <!-- 结算按钮 -->
    <view class="btn-settle" @click="settlement">
      结算({{checkedCount}})
    </view>
  </view>
</template>

<script>
  import {
    mapState,
    mapMutations,
    mapGetters
  } from 'vuex'
  export default {
    name: "my-settle",
    data() {
      return {
        s: 3
      };
    },
    computed: {
      ...mapState('m_cart', ['cart']),
      ...mapGetters('m_cart', ['checkedCount', 'total', 'checkedAllPrice']),
      ...mapState('m_user', ['token', 'address']),
      ...mapGetters('m_user', ['addressInfo']),
      // 动态判断全选状态！！！
      allChecked() {
        return this.checkedCount === this.total
      }
    },
    methods: {
      ...mapMutations('m_cart', ['updateAllState']),
      ...mapMutations('m_user', ['updateRedirectInfo']),
      // 改变全选状态
      changeAllState() {
        this.updateAllState(!this.allChecked)
      },
      // 结算及校验登录要求
      settlement() {
        if (!this.checkedCount) return uni.$showMsg('请选择结算商品')
        if (!this.addressInfo) return uni.$showMsg('请选择收获地址')
        // if(!this.token) return uni.$showMsg('请先登录！');
        // 延时自动跳转到登录页
        if (!this.token) return this.goMy()
        // 订单API
        this.payOrder()
      },
      async payOrder() {
        // 创建订单
        let orderObj = {
          order_price: 0.01,
          consignee_addr: this.addressInfo,
          goods: this.cart.filter(good => good.goods_state).map(x => ({
            goods_id: x.goods_id,
            goods_number: x.goods_count,
            goods_price: x.goods_price
          }))
        };
        const {
          data: res
        } = await uni.$http.post('/api/public/v1/my/orders/create', orderObj);
        if (res.meta.status !== 200) return uni.$showMsg('创建订单失败！')
        // console.log(res);
        // 1.3 得到服务器响应的“订单编号”
        const orderNumber = res.message.order_number
        // console.log(orderNumber);
        // 订单预支付
        const {
          data: res1
        } = await uni.$http.post('/api/public/v1/my/orders/req_unifiedorder', {
          order_number: orderNumber
        })
        // console.log(res1);
        if (res1.meta.status !== 200) return uni.$showMsg('预付订单生成失败！')
        const payInfo = res1.message.pay;
        // console.log(payInfo);
        uni.requestPayment({
          provider: 'wxpay',
         	timeStamp: payInfo.timeStamp,
          nonceStr: payInfo.nonceStr,
          package: payInfo.package,
          signType: payInfo.signType,
          paySign: payInfo.paySign,
          async success() {
            const {
              data: res2
            } = await uni.$http.post('/api/public/v1/my/orders/chkOrder', {
              order_number: orderNumber
            })
            uni.showToast({
              title: '订单支付完成！',
              icon: 'success'
            })
          },
          fail: function(err) {
            // 未完成支付
            return uni.$showMsg('订单功能无权限！')
          }
        });
      },
      // 自动进入我的登录页面提示
      showTip(n) {
        uni.showToast({
          title: `请登录后再结算! ${n}秒后自动跳转到登录页`,
          duration: 1500,
          // 必须设置图标，不然提示字数会受限
          icon: 'none',
          mask: true
        });
      },
      // 自动进入登录页定时器
      goMy() {
        this.showTip(this.s)
        var timer = setInterval(() => {
          this.s--;
          if (this.s <= 0) {
            clearInterval(timer),
              uni.switchTab({
                url: "/pages/my/my",
                // 跳转信息的存储
                success: () => {
                  let object = {
                    openType: 'switchTab',
                    from: '/pages/cart/cart'
                  }
                  this.updateRedirectInfo(object)
                }
              });
            return this.s = 3;
          }
          this.showTip(this.s)
        }, 1000)
        this.s = 3;
      },

    },
    filters: {
      toFixed(data) {
        return data.toFixed(2)
      }
    }
  }
</script>

<style lang="less" scoped>
  .my-settle-container {
    position: fixed;
    bottom: 0;
    left: 0;
    height: 50px;
    right: 0;
    background-color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    padding-left: 5px;

    .radio {
      display: flex;
      align-items: center;
    }

    .amount {
      color: #c00000;
      font-weight: bold;
    }

    .btn-settle {
      height: 50px;
      line-height: 50px;
      padding: 0 10px;
      text-align: center;
      background-color: #c00000;
      color: #fff;
      min-width: 100px;
    }
  }
</style>
